package com.atguigu.tingshu.user.strategy.impl;

import cn.hutool.core.date.DateUtil;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserVipService;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserVipServiceMapper;
import com.atguigu.tingshu.user.service.VipServiceConfigService;
import com.atguigu.tingshu.user.strategy.StrategyFactory;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashSet;

@Component("1003")
@Slf4j
public class VipStrategy implements StrategyFactory {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private VipServiceConfigService vipServiceConfigService;

    @Autowired
    private UserVipServiceMapper userVipServiceMapper;


    @Override
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        log.info("处理购买项目类型为：VIP会员");
// VIP
        // 重复提交调用,导致重复保存,所以先利用订单号(唯一性)查询数据库
        LambdaQueryWrapper<UserVipService> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserVipService::getOrderNo,userPaidRecordVo.getOrderNo());
        Long count = userVipServiceMapper.selectCount(wrapper);
        if(count > 0) return;

        //根据VIP套餐ID查询套餐信息-得到VIP会员服务月数
        Long vipConfigId = userPaidRecordVo.getItemIdList().get(0);
        VipServiceConfig vipServiceConfig = vipServiceConfigService.getById(vipConfigId);
        Integer serviceMonth = vipServiceConfig.getServiceMonth();

        // 查询用户是否为VIP，是则延长事件，不是则新增
        UserInfo userInfo = userInfoMapper.selectById(userPaidRecordVo.getUserId());
        Integer isVip = userInfo.getIsVip();
        Date vipExpireTime = userInfo.getVipExpireTime();

        // VIP记录表
        UserVipService userVipService = new UserVipService();
        userVipService.setUserId(userPaidRecordVo.getUserId());
        userVipService.setOrderNo(userPaidRecordVo.getOrderNo());

        if(isVip == 1 && vipExpireTime.after(new Date())){
            userVipService.setStartTime(vipExpireTime);
            userVipService.setExpireTime(DateUtil.offsetMonth(vipExpireTime,serviceMonth));
        }else {
            userVipService.setStartTime(new Date());
            userVipService.setExpireTime(DateUtil.offsetMonth(new Date(),serviceMonth));
        }
        // 保存VIP订单记录
        userVipServiceMapper.insert(userVipService);
        // 更新用户记录
        userInfo.setVipExpireTime(userVipService.getExpireTime());
        userInfo.setIsVip(1);
        userInfoMapper.updateById(userInfo);



    }
}
